package com.bwie.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.mapper.UserMapper;
import com.bwie.pojo.TbUser;
import com.bwie.service.UserService;
import com.bwie.utils.R;
import com.bwie.vo.LoginVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.cli.Digest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Title:
 * @BelongProjecet practice2
 * @BelongPackage com.bwie.service.impl
 * @Description:
 * @Copyright 研发一部
 * @Author: Mr.yan
 * @Date: 2024/6/7 9:39
 * @Version V1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public R userLogin(LoginVo loginVo) {
        //1.判断输入的用户名是否存在
        TbUser tbUser = userMapper.selectOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserName, loginVo.getUserName())
        );
        if (tbUser == null){
            return R.error(404,"该用户不存在，，请重新输入");
        }

        //2.密码加密
        String bcrypt = DigestUtil.bcrypt(loginVo.getPassword());
        System.out.println(bcrypt);

        //3.判断密码是否正确
        boolean b = DigestUtil.bcryptCheck(loginVo.getPassword(), tbUser.getPassword());
        if (!b){
            return R.error(500,"密码输入错误");
        }

        //4.生成token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").setIssuedAt(new Date())
                .claim("id", tbUser.getId())
                .claim("role",tbUser.getUserRole())
                .compact();

        tbUser.setToken(token);

        //5.设置有效期
        String tokenKey = "token-"+tbUser.getId();
        stringRedisTemplate.opsForValue().set(tokenKey,token,30, TimeUnit.MINUTES);

        return R.success(tbUser);
    }
}
